package net.oschina.kjtang.qywx.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.oschina.kjtang.qywx.api.entity.message.TextMessage;
import net.oschina.kjtang.qywx.api.service.MessageService;
import net.oschina.kjtang.qywx.common.component.httpclient.HttpClientComponent;
import net.oschina.kjtang.qywx.common.component.httpclient.HttpResult;
import net.oschina.kjtang.qywx.common.constants.RCodeConstants;
import net.oschina.kjtang.qywx.common.constants.WxAPIConstants;
import net.oschina.kjtang.qywx.common.exception.RCodeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by kjtang on 2017/12/6.
 *  消息推送
 */
@Transactional
@Service
public class MessageServiceImpl implements MessageService {

    private Logger logger = LoggerFactory.getLogger(MessageServiceImpl.class);

    @Autowired
    private HttpClientComponent httpClientComponent;

    @Override
    public void pushTextMessage(TextMessage message, String accessToken) throws RCodeException {
        try {
            String messageJson = JSON.toJSONString(message);
            System.out.println("发送的信息是:"+messageJson);
            HttpResult httpResult = this.httpClientComponent.doPostJson(WxAPIConstants.MESSAGE_PUSH_URL.replace("ACCESS_TOKEN", accessToken), messageJson);
            if(httpResult.getStatus()==200){
                JSONObject jsonObject = JSON.parseObject(httpResult.getData());
                if(jsonObject!=null){
                    int errcode = jsonObject.getIntValue("errcode");
                    String errmsg = jsonObject.getString("errmsg");
                    if(errcode!=0){
                        logger.info("[文本消息推送]", "pushTextMessage response:{}", new Object[]{jsonObject.toJSONString()});
                        throw  new RCodeException(errcode,new RuntimeException(errmsg));
                    }
                }else{
                    throw  new RCodeException(RCodeConstants.FAIL,new RuntimeException("部门更新失败"));
                }
            }
        }catch (Exception e){

        }
    }

}
